import 'dart:ffi';

import 'package:just_audio/just_audio.dart';

class AudioPlayerManager {
  static final AudioPlayerManager _instance = AudioPlayerManager._internal();

  factory AudioPlayerManager() => _instance;

  AudioPlayerManager._internal() {
    _audioPlayer = AudioPlayer();
  }

  late final AudioPlayer _audioPlayer;
  List<String> _audioUrls = [];
  int _currentIndex = 0;

  List<String> get audioUrls => _audioUrls;

  int get currentIndex => _currentIndex;

  final playlist = ConcatenatingAudioSource(
    useLazyPreparation: true,
    shuffleOrder: DefaultShuffleOrder(),
    children: [],
  );

  void setAudioUrls(List<String> urls) async {
    if (urls.isEmpty) {
      playlist.clear();
      audioUrls.clear();
    }
    _audioUrls = urls;
    for (int i = 0; i < urls.length; i++) {
      var vo = urls[i];
      playlist.add(AudioSource.uri(
        Uri.parse(vo),
      ));
    }
    await _audioPlayer.setAudioSource(playlist);
  }

  Future<void> playShufftle() async {
    if (_audioUrls.isEmpty) {
      throw Exception("No audio URLs set");
    }
    _audioPlayer.setShuffleModeEnabled(true);
    print("我llll乱序播放了！");
    _audioPlayer.setLoopMode(LoopMode.all);
    await _audioPlayer.play();
  }

  Future<void> playSort() async {
    if (_audioUrls.isEmpty) {
      throw Exception("No audio URLs set");
    }
    _audioPlayer.setShuffleModeEnabled(false);
    print("我sss顺序播放了！");
    await _audioPlayer.play();
  }

  Future<void> pause() async {
    await _audioPlayer.pause();
  }

  Future<void> stop() async {
    print("stop播放了！");
    await _audioPlayer.stop();
  }

  Future<void> seek(int index) async {
    _audioPlayer.seek(Duration.zero, index: index);
  }

  Future<void> next() async {
    await _audioPlayer.seekToNext();
  }
}
